<template>
  <cu-layout :bgStyle="{ color: '#ffffff' }" :navProp="{ placeholder: true }">
    <view :class="[`${prefixCls}-ocr-container`]" :style="{ height: step === 1 ? `calc(100vh - ${$Platform.navbar}px)` : '' }">
      <template v-if="step === 0">
        <view class="ID-card" v-for="(item, index) in papersImages" :key="index">
          <template v-if="!item.value">
            <view class="subscript-container" @click="handleUploadImage(index)">
              <image class="left-top" :src="$CDN('/common/static/images/left-top-frame.png')"></image>
              <image class="right-top" :src="$CDN('/common/static/images/right-top-frame.png')"></image>
              <image class="left-bottom" :src="$CDN('/common/static/images/left-bottom-frame.png')"></image>
              <image class="right-bottom" :src="$CDN('/common/static/images/right-bottom-frame.png')"></image>
              <image class="preview" :src="$CDN(`/common/static/images/${item.preview}`)"></image>
              <image class="upload-image" :src="$CDN('/common/static/images/camera.png')"></image>
            </view>
            <span class="tips">{{ item.tips }}</span>
          </template>
          <template v-else>
            <view class="image-container" @click="handleUploadImage(index)">
              <image class="upload-image" :src="$CDN('/common/static/images/camera.png')"></image>
              <image class="value-image" :src="item.value"></image>
            </view>
          </template>
        </view>
        <view class="agreement-container">
          <uv-checkbox-group v-model="agreement" :activeColor="theme" shape="circle" :labelDisabled="true">
            <uv-checkbox labelSize="10" :name="true">
              <template #default>
                <view style="font-size: 10px"> 我们将收集您的姓名和证件号码，仅用于实名认证<text class="agreement" @click="handleAgreement">《实名认证协议》</text></view>
              </template>
            </uv-checkbox>
          </uv-checkbox-group>
          <!-- <text class="item"> 《用户协议》 </text> -->
        </view>
        <uv-button customStyle="margin: 20px 0" type="primary" text="识别" @click="submit"></uv-button>
        <view class="text">根据电子合同法的规定，需要验证是本人签署，所以需要客户提供相关身份信息，在此页面之前有注明相关使用目的及信息安全使用的说明。</view>
        <view class="text">其他证件（护照、军官证、港澳台居住证）请联系门店管家进行实名认证</view>
      </template>
      <template v-else>
        <view class="auth-container">
          <swiper class="swiper" circular :indicator-dots="true" :autoplay="true" :interval="2000" :duration="500">
            <swiper-item v-for="(item, index) in papersImages" :key="index" class="swiper-item">
              <image class="swiper-value" :src="item.value"></image>
            </swiper-item>
          </swiper>
          <view class="data-info padding-right-0">
            <uv-input border="bottom" inputAlign="right" disabledColor="white" color="#999999" placeholder="请输入姓名" v-model="identityForm.name">
              <template v-slot:prefix>
                <uv-text text="真实姓名" size="13" margin="10rpx 0"></uv-text>
              </template>
            </uv-input>
            <uv-input border="bottom" inputAlign="right" disabledColor="white" color="#999999" placeholder="请输入身份证号" v-model="identityForm.card_num">
              <template v-slot:prefix>
                <uv-text text="身份证号" size="13" margin="10rpx 0"></uv-text>
              </template>
            </uv-input>
            <view class="tips-container">
              <view class="text">· 请分别确认将建正面、证件反面</view>
              <view class="text">· 该信息将作为承租人租约信息，若非本人，请在个人中心页面退出登录后，并注册您本人的身份相关信息。</view>
            </view>
            <view class="fixed-button" :style="{ bottom: `${safeAreaInsets}rpx` }">
              <uv-button type="primary" text="返回修改" :plain="true" customStyle="margin-top: 10px" @click="previousStep"></uv-button>
              <uv-button type="primary" text="提交确认" customStyle="margin-top: 10px" @click="stepSubmit"></uv-button>
            </view>
          </view>
        </view>
      </template>
      <popupRecognition ref="ref-popupRecognition"></popupRecognition>
    </view>
  </cu-layout>
</template>

<script>
import { getSignedUrl, uploadImg } from '@/api/common'
import { confirmAuthInfo, identity_ocr } from '@/api/user'

import popupRecognition from '@/pages/components/popupRecognition.vue'
import { mapActions, mapGetters, mapMutations } from 'vuex'
export default {
  name: 'ocr',
  components: {
    popupRecognition,
  },
  mixins: [],
  props: {},
  data() {
    return {
      step: 0,
      agreement: [],
      safeAreaInsets: 0,
      identityForm: {
        name: '',
        card_num: '',
        valid_date_begin: '',
        valid_date_end: '',
      },
      papersImages: [
        {
          value: '',
          field: 'identityImage',
          tips: '请上传身份证头像照',
          preview: 'portrait.png',
        },
        {
          value: '',
          field: 'identityBackImage',
          tips: '请上传身份证国徽照',
          preview: 'national-emblem.png',
        },
      ],
    }
  },
  // 侦听属性
  watch: {},
  // 计算属性
  computed: {
    ...mapGetters(['cameraUrl', 'theme']),
  },
  // 监听页面加载，该钩子被调用时data,computed,function,watch,props,slots已设置完成
  onLoad(options) {
    this.safeAreaInsets = this.$Platform.device.safeAreaInsets.bottom || 0
  },
  // 监听页面显示，页面每次出现在屏幕上都触发
  async onShow() {
    //#ifdef MP
    const { certificatesIndex } = this.$Route.query
    if (certificatesIndex != undefined) {
      // const signedUrl = await this.getSignedUrl(this.cameraUrl?.uploadUrl)
      this.papersImages[certificatesIndex].value = this.cameraUrl?.uploadUrl
      this.$Route.query.certificatesIndex = undefined
      this.SET_CAMERA_URL('')
    }
    //#endif
  },
  // 监听页面初次渲染完成，此时组件已挂载完成
  onReady() {},
  // 下拉刷新
  onPullDownRefresh() {},
  // 加载更多
  onReachBottom() {},

  created() {},
  mounted() {},
  destroyed() {},
  methods: {
    ...mapMutations('app', ['SET_CAMERA_URL']),
    ...mapActions([]),
    async getSignedUrl(url) {
      const res = await getSignedUrl({ url })
      return res
    },
    async handleUploadImage(index) {
      // 微信小程序环境
      //#ifdef MP
      this.$Route.query.certificatesIndex = index
      this.$ROUTE.go('/pages/common/camera')
      //#endif

      // 如果是app环境 或者 h5环境
      //#ifdef APP-PLUS || H5
      uni.chooseImage({
        count: 1,
        success: async (res) => {
          const { tempFiles } = res
          const file = tempFiles[0]
          const params = {
            filePath: file.path,
            name: 'upfile',
            formData: {
              filename: file.name,
            },
          }
          const { data } = await uploadImg(params)
          this.papersImages[index].value = data?.signedUrl
        },
      })
      //#endif
    },
    handleAgreement() {
      this.$ROUTE.go('/pages/subpackage/privacy-policy/privacy-detail?title=实名认证&subtitle=face_agreement')
    },
    async submit() {
      if (!this.agreement.length) return uni.$uv.toast('同意授权后才能进行实名认证')
      const identityImage = this.papersImages.find((v) => v.field == 'identityImage').value.replace(/\?x-oss-process=style.*/, '')
      const identityBackImage = this.papersImages.find((v) => v.field == 'identityBackImage').value.replace(/\?x-oss-process=style.*/, '')
      if (!identityImage || !identityBackImage) return uni.$uv.toast('请上传身份信息')
      const { data, errcode } = await identity_ocr({ identityImage, identityBackImage })
      if (errcode === 0) {
        this.step++
        for (let key in this.identityForm) {
          this.identityForm[key] = data[key] || ''
        }
      } else {
        this.step++
      }
    },
    previousStep() {
      this.step = 0
    },
    async stepSubmit() {
      const { errcode } = await confirmAuthInfo({ ...this.identityForm })
      if (errcode === 0) {
        this.$refs['ref-popupRecognition'].handleOpen({ scene: 'auth' })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.#{prefixCls('ocr-container')} {
  position: relative;
  background: white;
  box-sizing: border-box;
  padding: 20px 15px;
  .ID-card {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    border: 1px dashed #439dbc;
    margin: 20px auto 0;
    border-radius: 4px;
    width: 343px;
    height: 216px;
    position: relative;

    .subscript-container {
      width: 277px;
      height: 164px;
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      .preview {
        width: 183px;
        height: 116px;
        border-radius: 8rpx;
      }
      .upload-image {
        position: absolute;
        width: 48px;
        height: 48px;
      }
      .left-top {
        width: 20px;
        height: 20px;
        position: absolute;
        left: 0;
        top: 0;
      }
      .right-top {
        width: 20px;
        height: 20px;
        position: absolute;
        right: 0;
        top: 0;
      }
      .left-bottom {
        width: 20px;
        height: 20px;
        position: absolute;
        left: 0;
        bottom: 0;
      }
      .right-bottom {
        width: 20px;
        height: 20px;
        position: absolute;
        right: 0;
        bottom: 0;
      }
    }
    .image-container {
      width: 100%;
      height: 100%;
      position: relative;
      // display: flex;
      .value-image {
        width: 100%;
        height: 100%;
      }
      .upload-image {
        position: absolute;
        width: 48px;
        height: 48px;
        left: 0;
        top: 0;
        bottom: 0;
        right: 0;
        margin: auto;
        z-index: 2;
      }
    }
    .tips {
      position: absolute;
      bottom: 20px;

      font-weight: 400;
      font-size: 14px;
      color: #999999;
      line-height: 14px;
    }
  }

  .text {
    color: $uv-primary;
    font-size: 12px;
    text-indent: 24px;
    margin-bottom: 10px;
  }
}
.swiper {
  padding: 15px 20px;
  background: white;
  height: 218px;
}
.swiper-item {
  display: block;
  height: 218px;
  line-height: 218px;
  text-align: center;
  box-sizing: border-box;
  padding: 0 10px;
}
.swiper-value {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}
.tips-container {
  padding: 40rpx 20rpx;
  .text {
    margin-bottom: 10rpx;
    font-size: 24rpx;
    line-height: 40rpx;
    color: #666666;
    text-indent: unset;
  }
}
.agreement-container {
  padding: 20rpx 0 0;
  .agreement {
    color: $uv-primary;
  }
}
.fixed-button {
  position: fixed;
  left: 0;
  z-index: 2;
  width: 100%;
  background: linear-gradient(to bottom, white, #f5f5f5);
  padding: 20rpx 30rpx;
  box-sizing: border-box;
  border-top: 1px solid #f1f1f1;
  display: flex;
  ::v-deep .uv-button-wrapper {
    flex: 1;
    margin: 0 15px;
  }
}
</style>
